﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MFG_MaterialPreparationEdit.aspx.cs" Inherits="JYH.Web.MES.MFG.UI.MFG_MaterialPreparationEdit" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>备料单明细添加</title>
</head>
<script type="text/javascript">
    function LoadItem(rows) {
        $("#hTradeOrderID").val(rows.TradeOrderID);
        $('#hFromWarehouseID').val(rows.FromWarehouseID);
        $('#tTradeOrderNO').textbox('setValue', rows.TradeOrderNO);
        $('#tCreateTime').textbox('setValue', rows.CreateTime);
        $('#tSourceOrderNO').textbox('setValue', rows.SourceOrderNO);
        $('#tTradeQty').textbox('setValue', rows.TradeQty);
        $('#tProductNO').textbox('setValue', rows.ProductNO);
        $('#tRemark').textbox('setValue', rows.Remark);
    }
    $(function () {
        // 使用window.location.href获取当前URL
        const url = new URL(window.location.href);
        // 使用URLSearchParams接口获取URL参数
        const params = new URLSearchParams(url.search);
        const pa = JSON.parse(decodeURIComponent(params.get('params')));
        // 初始化
        if (pa != null) {
            LoadItem(pa);
            const view = params.get('view');
            if (view == "view") {
                /* $("#A1").style.display= "none";*/
                $('#SaveItems').hide();
                $('#ExeclTo').hide();
                $('#SingleStation').hide();
                $('#OrderStation').hide();
            }
        } else {
            $('#tb').find('input.easyui-textbox').textbox('setValue', '');
        }
        $('#s').on('dblclick', function () {
            $('#MaterialDialog').find('input.easyui-textbox').textbox('setValue', '');
            $('#MaterialDialog').dialog('open');
            MaterialLocal();
        });
        //收料明细
        $('#ItemDate').datagrid({
            pageSize: 20,
            loadMsg: "正在接收数据...",
            method: 'Get',
            iconCls: 'icon-reload',
            url: '/api/WMS/QueryWmsTradeSource',
            queryParams: {
                TradeOrderID: $("#hTradeOrderID").val(),
                MaterialNO: "",
                sort: "",
                order: ""
            },
            height: window.innerHeight - 150,
            idField: 'TradeSourceID',
            striped: true,      //隔行变色
            singleSelect: true, //是否单选
            pagination: true,   //分页控件  
            scrollbarSize: 0,
            fitColumns: true,
            columns: [[
                {
                    field: 'TradeSourceID', // 复选框字段
                    checkbox: true // 表示这是一个复选框列
                },
                { field: 'MaterialNO', title: '物料编号', width: 100 },
                { field: 'MaterialName', title: '物料名称', width: 100 },
                { field: 'MaterialDesc', title: '物料规格' },
                ///*       { field: 'BatchNO', title: '物料批号', width: 150 },*/
                { field: 'UnitQty', title: '单位用量', width: 70 },
                { field: 'RequestQty', title: '需求总数', width: 70, sortable: true },
                { field: 'CalculateQty', title: '算料数量', width: 70 },
                { field: 'ActionQty', title: '扫描数量', width: 70 },
                { field: 'LackQty', title: '缺料数量', width: 70 },
                { field: 'StationNO', title: '发料站位', width: 100 },
                { field: 'IsLeadName', title: '含铅', width: 70 },
                { field: 'IsTinningName', title: '搪锡', width: 70 }
            ]],
            loadFilter: function (data) {
                return JSON.parse(data);
            },
            rowStyler: function (index, row) {
                if (row.LackQty <= "0") {
                    return 'background-color:#C8E6C9;'; //绿色背景
                }
            },
            toolbar: "#toolbar",
            rownumbers: true,   //行号 
            onLoadSuccess: function (data) {
                $('#ItemDate').datagrid("fillRows");
                $('#ItemDate').datagrid('resize');
            },
            onSortColumn: function (sort, order) {
                $("#hSort").val(order);
                $("#hOrder").val(sort);
            }
        });

        //条码明细
        $('#CodeItem').datagrid({
            pageSize: 20,
            loadMsg: "正在接收数据...",
            method: 'Get',
            iconCls: 'icon-reload',
            url: '/api/WMS/QueryWmsTradebarcode',
            queryParams: {
                TradeOrderID: $("#hTradeOrderID").val(),
                MaterialNO: "",
                sort: "",
                order: ""
            },
            height: window.innerHeight - 150,
            idField: 'TradebarcodeID',
            striped: true,      //隔行变色
            singleSelect: true, //是否单选
            pagination: true,   //分页控件  
            scrollbarSize: 0,
            fitColumns: true,
            columns: [[
                {
                    field: 'TradebarcodeID', // 复选框字段
                    checkbox: true // 表示这是一个复选框列
                },
                { field: 'RStateName', title: '记录状态', width: 80, formatter: setColumnForeColor },
                { field: 'BarcodeNO', title: '条码编号', width: 100 },
                { field: 'MaterialNO', title: '物料编号', width: 100 },
                { field: 'MaterialName', title: '物料名称' },
                { field: 'MaterialDesc', title: '物料规格' },
                { field: 'BatchNO', title: '物料批号', width: 150 },
                { field: 'StationNO', title: '发料站位', width: 100 },
                { field: 'Qty', title: '数量', width: 70, sortable: true },
                { field: 'WarehouseName', title: '库位名称' },
                { field: 'StorageNO', title: '库位编号' },
                { field: 'RackNO', title: '料架编号' },
                { field: 'LampNO', title: '灯珠编号' }

            ]],
            loadFilter: function (data) {
                return JSON.parse(data);
            },
            toolbar: "#CodeBar",
            rownumbers: true,   //行号 
            onLoadSuccess: function (data) {
                $('#CodeItem').datagrid("fillRows");
                $('#CodeItem').datagrid('resize');
            },
            onSortColumn: function (sort, order) {
                $("#hSort").val(order);
                $("#hOrder").val(sort);
            }
        });
        // 下拉框加载 - 仓库
        $('#tFromWarehouseID').combobox({
            url: '/api/BAS/GetWarehouseInfo',
            method: 'POST',
            valueField: 'WarehouseID',
            textField: 'WarehouseName',
            panelHeight: 'auto',
            editable: false,
            label: '备料仓库:',
            required: true,
            onLoadSuccess: function (data) {
                // 获取隐藏字段的值
                var hiddenValue = $('#hFromWarehouseID').val();
                if (hiddenValue) {
                    // 如果隐藏字段有值，尝试匹配并选中
                    var matched = false;
                    $.each(data, function (index, item) {
                        if (item.WarehouseID == hiddenValue) {
                            $('#tFromWarehouseID').combobox('setValue', item.WarehouseID);
                            matched = true;
                            return false; // 退出循环
                        }
                    });
                } else {
                    // 如果隐藏字段没有值，默认选中第二个(确保数据长度大于1)
                    if (data && data.length > 1) {
                        $('#tFromWarehouseID').combobox('setValue', data[1].WarehouseID);
                        $('#hFromWarehouseID').val(data[1].WarehouseID); // 同步到隐藏字段
                    } else if (data && data.length === 1) {
                        // 如果只有一条数据，选中它
                        $('#tFromWarehouseID').combobox('setValue', data[0].WarehouseID);
                        $('#hFromWarehouseID').val(data[0].WarehouseID);
                    }
                }
            },
            onLoadError: function (error) {
                console.error('仓库加载失败:', error);
            },
            onChange: function (newVal) {
                $('#hFromWarehouseID').val(newVal); // 更新隐藏字段
            }
        });

        $('#tts').datagrid({
            loadMsg: "正在接收数据...",
            iconCls: 'icon-reload',
            url: '',
            idField: 'MaterialID',
            autoRowHeight: false,
            fitColumns: false,
            scrollbarSize: 0,
            height: document.documentElement.clientHeight - 250,
            pageSize: 20,
            sortable: true,
            striped: true,      //隔行变色
            singleSelect: true, //是否单选
            pagination: true,   //分页控件  
            rownumbers: true,
            columns: [[
                { field: 'IsSelect', checkbox: true },
                { field: 'MaterialID', hidden: true },
                //{ field: 'MaterialType', hidden: true },
                { field: 'MaterialNO', width: 150, title: '物料编号', sortable: true },
                { field: 'MaterialName', width: 250, title: '物料名称' },
                { field: 'MaterialDesc', width: 350, title: '物料规格' }


            ]],
            onDblClickRow: function (index, row) {
                if (row == null) {
                    Alert("请选择一行数据");
                    return false;
                }
                $("#tProductNO").textbox('setValue', row.MaterialNO);
                $('#MaterialDialog').dialog('close');
            },
            loadFilter: function (data) {
                if (data.d) {
                    return data.d;
                } else {
                    return JSON.parse(data);
                }

            }

        });


        $(window).resize(function () {
            $('#ItemDate').datagrid('resize');

        });
    })

    function myformatter(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
    }
    function myparser(s) {
        if (!s) return new Date();
        var ss = (s.split('-'));
        var y = parseInt(ss[0], 10);
        var m = parseInt(ss[1], 10);
        var d = parseInt(ss[2], 10);
        if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
            return new Date(y, m - 1, d);
        } else {
            return new Date();
        }
    }
    //新增保存
    function ItemSave() {
        if (!validateForm()) {
            return;
        }
        var url = "/api/WMS/SaveTradeInfo";
        var TradeOrderNO = $("#tTradeOrderNO").val();
        var datalist = {
            TradeOrderID: $("#hTradeOrderID").val(),
            TradeOrderNO: TradeOrderNO,
            CreateTime: $("#tCreateTime").val(),
            FromWarehouseID: $("#hFromWarehouseID").val(),
            ProductNO: $("#tProductNO").val(),
            SourceOrderNO: $("#tSourceOrderNO").val(),
            Remark: $("#tRemark").val(),
            TradeQty: $("#tTradeQty").val(),
            TradeType: 13
        }
        DataService.PostJson(url, datalist, (err, res) => {
            if (err) {
                Notice("success");
                console.log(res);
                $("#hTradeOrderID").val(res.Items[0].TradeOrderID);
                if (!TradeOrderNO || TradeOrderNO.trim() === "") {
                    $("#tTradeOrderNO").textbox("setValue", res.Items[0].TradeOrderNO);
                }
                SInItem();
            } else {
                Alert(res);
            }
        })
    }

    //收料明细检索
    function SInItem() {
        var TradeOrderID = $("#hTradeOrderID").val();
        var MaterialNO = $('#txtProduct').val();
        var sort = $("#hSort").val();
        var order = $("#hOrder").val();
        //排序字段
        $("#ItemDate").datagrid({
            method: 'Get',
            url: '/api/WMS/QueryWmsTradeSource',
            queryParams: {
                TradeOrderID: TradeOrderID,
                MaterialNO: MaterialNO,
                sort: sort,
                order: order
            },
            loadFilter: function (data) {
                return JSON.parse(data);
            }
        });
        $('#ItemDate').datagrid('unselectAll', 'true');
    }
    //条码明细检索
    function CodeItem() {
        var TradeOrderID = $("#hTradeOrderID").val();
        var MaterialNO = $('#txtCodeNO').val();
        var sort = $("#hSort").val();
        var order = $("#hOrder").val();
        //排序字段
        $("#CodeItem").datagrid({
            method: 'Get',
            url: '/api/WMS/QueryWmsTradebarcode',
            queryParams: {
                TradeOrderID: TradeOrderID,
                MaterialNO: MaterialNO,
                sort: sort,
                order: order
            },
            loadFilter: function (data) {
                return JSON.parse(data);
            }
        });
        $('#CodeItem').datagrid('unselectAll', 'true');
    }
    //根据状态改变值color
    function setColumnForeColor(value, row, index) {

        if (value == '新建' || value == 'Removed') {
            //红色
            return '<span style="color:gray;">' + value + '</span>';
        }
        if (value == '已确认' || value == 'Confirmed') {
            //绿色
            return '<span style="color:Green;">' + value + '</span>';
        }
        if (value == '已完成' || value == 'Completed') {
            //绿色
            return '<span style="color:#008B45;">' + value + '</span>';
        }
        return value;
    }
    //导入
    function ExeclTo() {
        OpenSubWindow("来源明细信息导入", "MFG/UI/MFG_MaterialPreparationView.aspx?params=" + $("#hTradeOrderID").val(), 500, 280, function () {
            SInItem();
        });
    }

    // 导出Excel
    function ExeclOut() {
        var TradeOrderID = $("#hTradeOrderID").val();
        if (!TradeOrderID) {
            Alert("请先保存主档信息");
            return;
        }
        // 构建导出URL
        var url = "/api/MFG/ExportMaterialPreparation?TradeOrderID=" + encodeURIComponent(TradeOrderID);
        DataService.GetExcelFile(url, function (err, data) {
            if (err) {
                Notice("success");

                // 生成当前日期时间字符串（格式：yyyyMMdd）
                const orderNo = $("#tTradeOrderNO").val();
                const now = new Date();
                const dateStr = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`;
                // 组合文件名
                const fileName = orderNo ? `${orderNo}_${dateStr}.xlsx` : `备料单_${dateStr}.xlsx`;
                // 创建下载链接
                const url = window.URL.createObjectURL(data.blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            }
            else {
                Alert(res);
            }
        })
    }
    //MaterialLocalLocal
    function MaterialLocal() {
        var MaterialNO = $("#DMaterialNO").val();
        var MaterialName = $("#DMaterialName").val();
        $("#tts").datagrid({
            url: '/api/BAS/QueryMaterial',
            method: 'Get',
            queryParams: {
                MaterialNO: MaterialNO,
                MaterialName: MaterialName,
                order: '',
                sort: ''
            },
            loadFilter: function (data) {
                if (data.d) {
                    return data.d;
                } else {
                    return JSON.parse(data);
                }

            }
        });
    }
</script>
<body>
    <style>
        /* 调整 EasyUI TextBox 的 label 间距 */
        .textbox-label {
            margin-right: -20px !important;
            margin-left: 20px !important;
        }
    </style>
    <form runat="server" id="ff">
        <%--排序隐藏值--%>
        <asp:HiddenField runat="server" ID="hSort" />
        <asp:HiddenField runat="server" ID="hOrder" />
        <asp:HiddenField runat="server" ID="hTradeOrderID" />
        <input type="hidden" id="hFromWarehouseID" />
        <div class="pagebox">
            <div class="cbox">
                <!--工具栏-->
                <div class="easyui-panel" style="padding: 15px; width: 100%;">
                    <div id="tb">
                        <ul class="flist">
                            <li>
                                <input class="easyui-textbox" type="text" id="tTradeOrderNO" runat="server" data-options="prompt:'保存自动生成',label:'备料单号:'" style="width: 250px; height: 35px; line-height: 35px;" />
                            </li>
                            <li>
                                <input class="easyui-datebox" id="tCreateTime" value="1" data-options="prompt:'备料日期',label:'备料日期:',formatter:myformatter,parser:myparser" style="width: 250px; height: 35px;" required />
                            </li>
                            <li id="s">
                                <input class="easyui-textbox" id="tProductNO" data-options="prompt:'双击获取',label:'产品料号:'" style="width: 350px; height: 35px;" required />
                            </li>
                            <li>
                                <input class="easyui-textbox" id="tTradeQty" type="number" data-options="prompt:'备料套数',   label:'备料套数:'" style="width: 220px; height: 35px;" required />
                            </li>
                        </ul>
                        <ul class="flist">
                            <li>
                                <input class="easyui-textbox" type="text" id="tSourceOrderNO" runat="server" data-options="label:'生产工单:'" style="width: 250px; height: 35px; line-height: 35px;" />
                            </li>
                            <li>
                                <input id="tFromWarehouseID" style="width: 250px; height: 35px; line-height: 35px;" />
                            </li>
                            <li>
                                <input class="easyui-textbox" id="tRemark" data-options="prompt:'',label:'备注:'" style="height: 35px; width: 490px;" />
                            </li>
                            <a href="javascript:;" class="easyui-linkbutton c1" onclick="ItemSave()" id="SaveItems" style="margin-left: 30px">保存主档</a>
                        </ul>
                    </div>

                </div>
            </div>
            <div class="cbox">
                <div id="shows" class="easyui-tabs" data-options="border:1" style="width: 100%;">
                    <div title="来源明细">
                        <table id="ItemDate"></table>
                    </div>
                    <div title="条码明细">
                        <table id="CodeItem"></table>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <div id="toolbar" style="padding: 5px; height: auto">
        <div style="margin-bottom: 5px;">
            <ul class="flist">
                <li>
                    <input class="easyui-textbox" type="text" id="txtProduct" data-options="prompt:'物料名称/编号'" style="width: 250px; height: 35px; line-height: 35px;" />
                </li>
                <a href="#" class="easyui-linkbutton" iconcls="icon-edit" plain="true" runat="server" id="SInItem" onclick="SInItem()">检索</a>
                <a href="#" class="easyui-linkbutton" iconcls="icon-undo" plain="true" runat="server" id="ExeclOut" onclick="ExeclOut()">导出</a>
                <a href="#" class="easyui-linkbutton" iconcls="icon-add" plain="true" runat="server" id="ExeclTo" onclick="ExeclTo()">导入</a>

            </ul>
        </div>
    </div>

    <div id="CodeBar" style="padding: 5px; height: auto">
        <div style="margin-bottom: 5px;">
            <ul class="flist">
                <li>
                    <input class="easyui-textbox" type="text" id="txtCodeNO" data-options="prompt:'物料/条码'" style="width: 250px; height: 35px; line-height: 35px;" />
                </li>
                <a href="#" class="easyui-linkbutton" iconcls="icon-edit" plain="true" runat="server" id="A1" onclick="CodeItem()">检索</a>
            </ul>
        </div>
    </div>

    <%--    物料检索dialog--%>
    <div id="MaterialDialog" class="easyui-dialog" title="Part List" style="width: 700px; height: 500px; padding: 5px" data-options="closed:true,modal:true">
        <div class="cbox">
            <ul class="flist">
                <li>
                    <input class="easyui-textbox" type="text" id="DMaterialNO" data-options="prompt:'请输入物料编号'" style="width: 350px; height: 35px; line-height: 35px;" /></li>
                <li>
                    <input class="easyui-textbox" type="text" id="DMaterialName" data-options="prompt:'请输入物料名称'" style="width: 350px; height: 35px; line-height: 35px;" />
                    <a href="javascript:void(0)" id="DMSearch" class="easyui-linkbutton c1" onclick="MaterialLocal()" data-options="iconCls:'icon-sousuo',selected:true">查询</a>
                </li>


            </ul>
        </div>
        <div class="cbox">
            <!--查询结果清单-->
            <table id="tts">
            </table>
        </div>
    </div>
</body>
</html>
